#include "drivewatcher.h"

DriveWatcher::DriveWatcher()
{
}

DriveWatcher::DriveWatcher(const char* driveLetter)
{
    _driveLetter = QString(driveLetter);

}

DriveWatcher::DriveWatcher(const QString &driveLetter)
{
    _driveLetter = driveLetter;
}
DriveWatcher::~DriveWatcher()
{
    this->wait();
    if(timer!=NULL)
        delete timer;
}

void DriveWatcher::run()
{
    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(checkDrive()));

    timer->setInterval(10*1000);
    timer->start();
    exec();
}

void DriveWatcher::reloadDrive()
{
    _driveInfo = VDrives();

}
void DriveWatcher::changeLetter(QString newLetter)
{
    _driveLetter = newLetter;
}

void DriveWatcher::checkDrive()
{
    Logger::log()<<"DriveWatcher::checkDrive()";
    QStringList mList = VDrives::getLogicalDrives();
    QChar letter = _driveLetter.at(0);
    qDebug() << "Checking Drives: "<<letter;
    Logger::log()<<"Checking Drives: "<<letter;

    //EjectVolume('H');
    //Loop through the logical drives
    for (int i = 0; i < mList.size(); ++i)
    {
        VDrives mDrive(mList.at(i));
        if(mDrive.Name().at(0)== letter)
        {
            if(mDrive.TotalNumberOfBytes()!=0)
            {
                if(mDrive.Label()!=_driveInfo.Label())
                {

                    _driveInfo = mDrive;
                    qDebug() << " Drive "<< mDrive.Name() <<"has a new disc";
                    Logger::log()<< " Drive "<< mDrive.Name() <<"has a new disc";
                    qDebug() << " - New Volume Serial Number: " <<  mDrive.VolumeSerialNumber();
                    qDebug() << " - Label: " <<  mDrive.Label();
                    Logger::log()<<  " - Label: " <<  mDrive.Label();
                    qDebug() << " - FileSystem: " <<  mDrive.FileSystem();
                    qDebug() << " - DriveType: " <<  mDrive.DriveType();
                    qDebug() << " - DriveTypeInt: " <<  mDrive.DriveTypeInt();
                    qDebug() << " - Free bytes: " << mDrive.FreeBytesAvailable();
                    qDebug() << " - Total Bytes: " << mDrive.TotalNumberOfBytes();
                    qDebug() << " - Total Free Bytes: " << mDrive.TotalNumberOfFreeBytes();
                    Logger::log()<<"emit discDetected()";
                    emit discDetected();
                }
            }
            else
            {
                _driveInfo = mDrive;
                qDebug() << " Drive "<< mDrive.Name() <<"is empty";
                Logger::log()<< " Drive "<< mDrive.Name() <<"is empty";

                emit discEmpty();
            }
        }
    }
}

